<template>
  <div class="plan-offer-list">
    <!-- 报价模式 -->
    <div class="summary-message">{{ summaryMessage }}</div>
    <el-table
      :data="localProjectPlans"
      row-key="id"
      stripe
      :expand-row-keys="expandRows"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-card class="offer-card">
            <h3>详细信息</h3>
            <table class="cus-table">
              <tr>
                <td>物料名称</td>
                <td>{{ scope.row.detail.materialName }}</td>
                <td>规格型号</td>
                <td>{{ scope.row.detail.model }}</td>
                <td>配置</td>
                <td>{{ scope.row.detail.configuration }}</td>
              </tr>
              <tr>
                <td>物料数量</td>
                <td>{{ scope.row.detail.amount }}</td>
                <td>计量单位</td>
                <td>{{ scope.row.detail.unit }}</td>
                <td>项目编号</td>
                <td>{{ scope.row.detail.projectNumber }}</td>
              </tr>
              <tr>
                <td>交货地点</td>
                <td>{{ scope.row.detail.deliveryPoints }}</td>
                <td>交货日期</td>
                <td>{{ scope.row.detail.deliveryDate | moment('YYYY-MM-DD') }}</td>
                <td>应用系统</td>
                <td>{{ scope.row.detail.applySystem }}</td>
              </tr>
            </table>
          </el-card>
          <el-card class="offer-card">
            <h3>报价项</h3>
            <el-form
              ref="offerForm"
              :rules="offerRules"
              :model="localOfferList[scope.$index]"
              label-width="100"
              label-position="top"
              :disabled="disabled"
            >
              <el-row :gutter="25">
                <el-col :span="8">
                  <el-form-item prop="model" label="规格型号">
                    <el-input v-model="localOfferList[scope.$index].detail.model"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="configuration" label="配置">
                    <el-input
                      v-model="localOfferList[scope.$index].detail.configuration"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="deliveryDate" label="交货日期">
                    <el-date-picker
                      v-model="localOfferList[scope.$index].detail.deliveryDate"
                      value-format="timestamp"
                      style="width: 100%;"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item prop="tax" label="税率">
                    <el-select
                      v-model="localOfferList[scope.$index].detail.tax"
                      @change="taxChanged(scope.$index)"
                    >
                      <el-option
                        v-for="item in TAX_RATE"
                        :key="item"
                        :value="item"
                        :label="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="unitPriceWithoutTax" label="未税单价(元)">
                    <el-input
                      v-model="localOfferList[scope.$index].unitPriceWithoutTax"
                      @input="calTax(scope.$index, 'untaxInput')"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="unitPriceWithTax" label="含税单价(元)">
                    <el-input
                      v-model="localOfferList[scope.$index].unitPriceWithTax"
                      @input="autoCombindPrice(scope.$index, 'taxInput')"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="combinedPrice" label="含税合价(元)">
                    <el-input
                      v-model="localOfferList[scope.$index].combinedPrice"
                      @input="updateTablePrice(scope.$index)"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column label="*物料名称">
        <template slot-scope="scope">
          <span>{{ scope.row.detail.materialName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="*规格型号">
        <template slot-scope="scope">
          <span>{{ scope.row.detail.model }}</span>
          <div
            class="diff-conf"
            v-if="
              localOfferList[scope.$index] &&
              scope.row.detail.model != localOfferList[scope.$index].detail.model
            "
          >
            {{ localOfferList[scope.$index].detail.model }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="*配置">
        <template slot-scope="scope">
          <span>{{ scope.row.detail.configuration }}</span>
          <div
            class="diff-conf"
            v-if="
              localOfferList[scope.$index] &&
              scope.row.detail.configuration != localOfferList[scope.$index].detail.configuration
            "
          >
            {{ localOfferList[scope.$index].detail.configuration }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="*税率/(实际提交税率)" width="140">
        <template slot-scope="scope">
          <span>
            <span>{{ scope.row.detail.tax }}</span>
            /
            <span
              :class="{
                'diff-conf': scope.row.detail.tax != localOfferList[scope.$index].detail.tax,
              }"
            >
              {{ localOfferList[scope.$index].detail.tax }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="交货日期" width="100">
        <template slot-scope="scope">
          <div>
            <div>{{ scope.row.detail.deliveryDate | moment('YYYY-MM-DD') }}</div>
            <div
              class="diff-conf"
              v-if="
                scope.row.detail.deliveryDate != localOfferList[scope.$index].detail.deliveryDate
              "
            >
              {{ localOfferList[scope.$index].detail.deliveryDate | moment('YYYY-MM-DD') }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="*物料数量" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.detail.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="*含税单价(元)">
        <template slot-scope="scope">
          <span>{{ currency(scope.row.detail.unitPriceWithTax) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="*合价(元)">
        <template slot-scope="scope">
          <span>{{ currency(scope.row.detail.combinedPrice) }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import { TAX_RATE } from '@/config';
  import { resultFormatter } from '@/utils';
  import { accMul, accAdd, accDiv, currency } from '@/utils/math';
  import nzh from '@/utils/nzh';
  import FormRuleConf from '@/FormRuleConf';

  export default {
    name: 'PlanOfferList',
    dicts: ['unit_list'],
    props: {
      projectPlans: {
        type: Array,
        default: () => [],
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      offerList: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        ...FormRuleConf.Offer,
        expandRows: [],
        localProjectPlans: [...this.projectPlans],
        localOfferList: [],
        summaryMessage: '',
        TAX_RATE,
      };
    },
    watch: {
      value(newVal, oldVal) {
        // 这里是为了更新summary的时候,不要被再次更新设置的
        if (oldVal.length === 0) {
          this.initOfferList();
        }
      },
    },
    mounted() {
      this.$EventBus.$on('expandAllPlan', (status) => {
        this.expandRows = status ? [] : this.localProjectPlans.map((v) => v.id);
      });

      this.initOfferList();
    },
    methods: {
      initOfferList() {
        if (this.offerList.length === 0) {
          this.localOfferList = this.localProjectPlans.map((plan) => {
            const { id } = plan;
            const {
              model,
              configuration,
              deliveryDate,
              tax,
              amount,
              materialName,
              combinedPrice,
            } = plan.detail;
            return {
              planId: id,
              detail: {
                model,
                configuration,
                deliveryDate,
                amount,
                tax,
                materialName,
              },
              offerAmount: amount,
              unitPriceWithTax: 0,
              unitPriceWithoutTax: 0,
              combinedPrice: 0,
            };
          });
        } else {
          this.localOfferList = this.offerList.map((plan) => {
            const {
              planId,
              detail,
              combinedPrice,
              offerAmount,
              unitPriceWithoutTax,
              unitPriceWithTax,
            } = plan;
            const { model, configuration, deliveryDate, amount, tax } = detail
              ? JSON.parse(detail)
              : {};
            return {
              planId,
              detail: {
                model,
                configuration,
                deliveryDate,
                amount,
                tax,
              },
              offerAmount,
              unitPriceWithTax,
              unitPriceWithoutTax,
              combinedPrice,
            };
          });

          this.localOfferList.forEach((offer, index) => {
            this.updateTablePrice(index);
          });
        }
      },
      taxChanged(index) {
        this.calTax(index);
      },
      toFixed2(price) {
        return price.toString().match(/^\d*(\.?\d{0,2})/g)[0] || null;
      },
      /**
       * 自动计算税后和合价
       */
      calTax(index, source) {
        let price = this.localOfferList[index].unitPriceWithoutTax;
        let priceWithTax = 0;
        if (price != '' && !isNaN(price)) {
          // 保证小数点只有两位
          this.$set(this.localOfferList[index], 'unitPriceWithoutTax', this.toFixed2(price));

          priceWithTax = accDiv(
            accMul(
              accAdd(this.localOfferList[index].detail.tax, 100),
              this.localOfferList[index].unitPriceWithoutTax,
            ),
            100,
          ).toString();
        } else {
          priceWithTax = '0';
        }

        this.$set(this.localOfferList[index], 'unitPriceWithTax', priceWithTax);
        //  计算后面的去
        this.autoCombindPrice(index, source);
      },
      /**
       * 自动计算合价
       */
      autoCombindPrice(index, source) {
        let price = this.localOfferList[index].unitPriceWithTax.toString();
        let combinedPrice = 0;
        if (price != '' && !isNaN(price)) {
          // 保证小数点只有两位
          this.$set(this.localOfferList[index], 'unitPriceWithTax', this.toFixed2(price));
          price = this.localOfferList[index].unitPriceWithTax.toString();

          // 计算合价
          combinedPrice = accMul(
            this.localOfferList[index].offerAmount,
            this.localOfferList[index].unitPriceWithTax,
          ).toString();
        } else {
          combinedPrice = '0';
        }

        // 更新实际报价
        this.$set(this.localOfferList[index], 'combinedPrice', combinedPrice);
        // 修改含税时,反推未税价格
        if (source === 'taxInput') {
          this.$set(
            this.localOfferList[index],
            'unitPriceWithoutTax',
            accDiv(price, accDiv(accAdd(this.localOfferList[index].detail.tax, 100), 100)).toFixed(
              2,
            ),
          );
        }

        this.updateTablePrice(index);
      },
      updateTablePrice(index) {
        // 更新表格 只是展示
        this.$set(
          this.localOfferList[index],
          'combinedPrice',
          this.toFixed2(this.localOfferList[index].combinedPrice),
        );
        this.$set(
          this.localProjectPlans[index].detail,
          'combinedPrice',
          this.toFixed2(this.localOfferList[index].combinedPrice),
        );
        this.$set(
          this.localProjectPlans[index].detail,
          'unitPriceWithTax',
          this.localOfferList[index].unitPriceWithTax,
        );
      },
      // updateSummaries() {
      //   this.localProjectPlans.push({});
      //   this.localProjectPlans.pop();
      // },
      getSummaries(params) {
        const { columns, data } = params;
        const sums = [];

        columns.forEach((column, index) => {
          if (index === columns.length - 1) {
            const total = data.reduce((prev, current, index) => {
              return accAdd(prev, current.detail.combinedPrice || 0);
            }, 0);
            this.summaryMessage = `总价: ${currency(total)} 元。 大写: ${nzh.toMoney(total)}`;
          }
        });

        return [];
      },
      validateForm() {
        this.expandRows = this.localProjectPlans.map((plan) => plan.id);
        return this.$refs['offerForm'].validate();
      },
      currency,
    },
  };
</script>

<style lang="scss" scoped>
  .plan-offer-list {
    .h4 {
      line-height: 30px;
      margin: 0;
    }
    .cus-table {
      td {
        min-width: 100px;
        max-width: 12.5%;
        line-height: 20px;
        padding: 5px;
        &:nth-child(odd) {
          width: 100px;
        }
      }
      /deep/ em {
        font-style: normal;
      }
    }

    .offer-card {
      h3 {
        margin: 5px 0;
        color: #666;
        display: flex;
        &:before {
          content: '';
          display: inline-block;
          border-left: 5px solid #41ba82;
          width: 0;
          height: 16px;
          margin-right: 5px;
        }
      }
    }

    .summary-message {
      text-align: right;
      font-size: 12px;
      font-weight: bolder;
      color: #ff2200;
      padding-bottom: 5px;
    }
  }
</style>
